<?php

class Permission_Controller_Admincp_Index extends Nuo_Controller_Admincp
{
	function execute($request)
	{
		Nuo::setVar('breadcrum', array(
			'toolbar' => 'admincp/permission',
			'title' => 'Manage Permission'
		));

		$roleId = $request -> getParam('role_id');

		$role = Nuo::getTable('permission/role') -> find($roleId) -> current();

		if (!$role)
		{
			$uri = Nuo::getUrl('admincp/permission', array('role_id' => 1));

			Nuo::redirect($uri);

			return;
		}

		$form = Nuo::getObject('permission/admincp/permission/edit', 'form');

		if ($request -> isGet())
		{

			$perms = Nuo::getApi('permission') -> loadPerm($roleId);

			foreach ($form->getChildren() as $ele)
			{
				$name = $ele -> getName();

				if (substr($name, 0, 1) == '_')
				{
					continue;
				}

				list($k1, $k2) = explode('_', $name, 2);

				$key = $k1 . '.' . $k2;

				$value = isset($perms[$key]) ? $perms[$key] : NULL;

				$ele -> setValue($value);
			}

		}

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			Nuo::getApi('permission') -> setPermission($roleId, $data);

		}

		return Nuo::getView() -> render('core/view/controller/admincp/edit', array('form' => $form));
	}

}
